How can I declare and initialize an array in Java?
How can I declare and initialize an array in Java?
28121-Jul-2023
Updated on 22-Jul-2023
Home / DeveloperSection / Forums / How can I declare and initialize an array in Java?
How can I declare and initialize an array in Java?
Aryan Kumar
22-Jul-2023There are two ways to declare and initialize an array in Java:
where
data_type
is the data type of the elements of the array,array_name
is the name of the array, andvalue1, value2, value3, ...
are the initial values of the array elements.For example, the following code declares and initializes an array of integers:
where
size
is the size of the array.For example, the following code declares an array of integers and then initializes the elements one by one:
Which method you use to declare and initialize an array depends on your specific needs. If you know the initial values of the array elements, then it is more efficient to declare and initialize the array in one step. However, if you do not know the initial values of the array elements, then you will need to declare the array and then initialize the elements one by one.